package com.zhaonongzi.tms.util;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FileUtil {
	
	public static Map<String, StringBuffer> readTxtFile(InputStream input){
	     Map<String, StringBuffer> map=new HashMap<String, StringBuffer>();
	 	   try {
	 		    String encoding="utf-8";
	          	InputStreamReader read = new InputStreamReader(input,encoding);//考虑到编码格式
	          	BufferedReader bufferedReader = new BufferedReader(read);
	          	StringBuffer original= new StringBuffer();
	          	String lineTxt =null;
	          	while((lineTxt = bufferedReader.readLine()) != null){
	          		  original.append(lineTxt).append("\r\n");
	          	}
	          read.close();
	          map.put("original",original);
			   } catch (Exception e) {
				 e.printStackTrace();
			}
 	    return map;
	}
	
	 public static void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException {   
			try {
				FileOutputStream fs=new FileOutputStream( path + "/"+ filename); 
			    byte[] buffer =new byte[1024*1024]; 
			    int byteread = 0; 
			    while ((byteread=stream.read(buffer))!=-1) 
			    { 
			       fs.write(buffer,0,byteread); 
			       fs.flush(); 
			    } 
			    fs.close(); 
			    stream.close();    
			} catch (Exception e) {
				e.printStackTrace();
			}  
    }

	/**
	 * 获取ResponseEntity来实现下载
	 * @param txt
	 * @param fileName
     * @return
     */
	public static ResponseEntity exportToDownload(String txt,String fileName) {
		try {
			fileName = new String(fileName.getBytes("utf-8"),"ISO-8859-1");
			//设置请求头内容,告诉浏览器代开下载窗口
			HttpHeaders headers = new HttpHeaders();
			headers.setContentDispositionFormData("attachment",fileName );
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return new ResponseEntity<byte[]>(txt.getBytes(),
					headers, HttpStatus.CREATED);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null ;
	}

}
